package com.facefun.druid;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@EnableConfigurationProperties(DruidProperties.class)
@ConditionalOnClass(DruidDataSource.class)
@ConditionalOnProperty(prefix="druid",name="url")
@AutoConfigureBefore(DruidAutoConfiguration.class)
public class DruidAutoConfiguration {

	@Autowired
	private DruidProperties properties;
	
	@Bean
	public DataSource dataSource(){
		DruidDataSource db=new DruidDataSource();
		db.setDriverClassName(properties.getDriverClass());
		db.setUrl(properties.getUrl());
		db.setUsername(properties.getUsername());
		db.setPassword(properties.getPassword());
		
		if(properties.getInitialSize()>0){
			db.setInitialSize(properties.getInitialSize());
		}
		if(properties.getMaxActive()>0){
			db.setMaxActive(db.getMaxActive());
		}
		if(properties.getMinIdle()>0){
			db.setMinIdle(properties.getMinIdle());
		}
		
		return db;
	}
	
}
